<!-- src/views/Player.vue -->
<template>
  <div class="player-container" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
    <div class="player-content">
      <!-- 视频播放器 -->
      <div v-if="currentContent && currentContent.contentType === 'video'" class="video-player">
        <video 
          ref="videoRef"
          :src="currentContent.filePath" 
          controls
          autoplay
          @ended="nextContent"
        />
      </div>
      
      <!-- 图片查看器 -->
      <div v-else-if="currentContent && currentContent.contentType === 'image'" class="image-viewer">
        <img :src="currentContent.filePath" :alt="currentContent.title || currentContent.filename" />
      </div>
      
      <!-- 内容信息 -->
      <div class="content-info">
        <h2>{{ currentContent?.title || currentContent?.filename }}</h2>
        <p v-if="currentContent?.description">{{ currentContent.description }}</p>
        
        <div class="tags" v-if="currentContent?.tags && currentContent.tags.length > 0">
          <span 
            v-for="tag in currentContent.tags" 
            :key="tag.id" 
            class="tag"
          >
            {{ tag.name }}
          </span>
        </div>
        
        <div class="actions">
          <el-rate
            v-model="rating"
            :max="5"
            @change="handleRatingChange"
            show-score
            score-template="{value} 分"
          />
          
          <el-button 
            :type="currentContent?.isFavorite ? 'danger' : 'default'" 
            :icon="currentContent?.isFavorite ? StarFilled : Star" 
            @click="toggleFavorite"
          >
            {{ currentContent?.isFavorite ? '取消收藏' : '收藏' }}
          </el-button>
        </div>
      </div>
      
      <!-- 滑动提示 -->
      <div class="swipe-hint" v-if="contents.length > 1">
        <span>向上/向下滑动切换内容</span>
      </div>
    </div>
    
    <!-- 返回按钮 -->
    <el-button 
      class="back-button" 
      type="primary" 
      @click="goBack"
      :icon="Back"
    >
      返回
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Star, StarFilled, Back } from '@element-plus/icons-vue';
import { useContentStore } from '../stores/content';
import type { Content } from '../types/models';

const route = useRoute();
const router = useRouter();
const contentStore = useContentStore();

const currentContent = ref<Content | null>(null);
const contents = ref<Content[]>([]);
const rating = ref<number>(0);
const videoRef = ref<HTMLVideoElement | null>(null);

// 触摸事件处理，用于滑动切换内容
const touchStartY = ref(0);
const touchEndY = ref(0);

// 初始化
onMounted(async () => {
  const id = Number(route.params.id);
  
  // 获取当前内容
  await contentStore.fetchContentById(id);
  currentContent.value = contentStore.currentContent;
  
  // 获取评分
  if (currentContent.value?.rating) {
    rating.value = currentContent.value.rating;
  }
  
  // 获取所有内容用于滑动切换
  await contentStore.fetchContents(0, 100); // 获取更多内容
  contents.value = contentStore.contents;
});

// 触摸开始事件
const handleTouchStart = (event: TouchEvent) => {
  touchStartY.value = event.changedTouches[0].screenY;
};

// 触摸结束事件
const handleTouchEnd = (event: TouchEvent) => {
  touchEndY.value = event.changedTouches[0].screenY;
  const distance = touchStartY.value - touchEndY.value;
  
  // 向上滑动（distance > 0）切换到下一个，向下滑动（distance < 0）切换到上一个
  if (Math.abs(distance) > 50) { // 最小滑动距离
    if (distance > 0) {
      nextContent(); // 向上滑动，下一个
    } else {
      prevContent(); // 向下滑动，上一个
    }
  }
};

// 下一个内容
const nextContent = () => {
  if (!currentContent.value) return;
  
  const currentIndex = contents.value.findIndex(c => c.id === currentContent.value?.id);
  if (currentIndex < contents.value.length - 1) {
    const nextId = contents.value[currentIndex + 1].id;
    router.push(`/player/${nextId}`);
    // 重新加载当前组件以显示新内容
    currentContent.value = contents.value[currentIndex + 1];
    updateContentInfo();
  }
};

// 上一个内容
const prevContent = () => {
  if (!currentContent.value) return;
  
  const currentIndex = contents.value.findIndex(c => c.id === currentContent.value?.id);
  if (currentIndex > 0) {
    const prevId = contents.value[currentIndex - 1].id;
    router.push(`/player/${prevId}`);
    // 重新加载当前组件以显示新内容
    currentContent.value = contents.value[currentIndex - 1];
    updateContentInfo();
  }
};

// 更新内容信息
const updateContentInfo = () => {
  if (currentContent.value?.rating) {
    rating.value = currentContent.value.rating;
  } else {
    rating.value = 0;
  }
  
  // 如果是视频，尝试播放
  if (currentContent.value?.contentType === 'video') {
    nextTick(() => {
      if (videoRef.value) {
        videoRef.value.play().catch(e => console.log('播放失败:', e));
      }
    });
  }
};

// 处理评分变化
const handleRatingChange = async (value: number) => {
  if (currentContent.value) {
    await contentStore.rateContent(currentContent.value.id, value);
  }
};

// 切换收藏
const toggleFavorite = async () => {
  if (currentContent.value) {
    await contentStore.toggleFavorite(currentContent.value.id);
    // 更新当前内容的收藏状态
    if (currentContent.value) {
      currentContent.value.isFavorite = !currentContent.value.isFavorite;
    }
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};
</script>

<style scoped>
.player-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.player-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.video-player,
.image-viewer {
  width: 100%;
  max-width: 800px;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-player video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  max-height: 70vh;
}

.image-viewer img {
  max-width: 90%;
  max-height: 70vh;
  object-fit: contain;
}

.content-info {
  width: 100%;
  max-width: 800px;
  padding: 1rem;
  color: white;
  text-align: center;
  background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
  margin-top: -50px;
  position: relative;
}

.content-info h2 {
  margin: 0 0 0.5rem 0;
  font-size: 1.5rem;
}

.tags {
  margin: 1rem 0;
}

.tag {
  display: inline-block;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
  font-size: 0.9rem;
  margin: 0.25rem;
}

.actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  margin-top: 1rem;
}

.swipe-hint {
  position: absolute;
  bottom: 100px;
  color: white;
  text-align: center;
  width: 100%;
  font-size: 0.9rem;
  opacity: 0.7;
}

.back-button {
  position: absolute;
  top: 1rem;
  left: 1rem;
  z-index: 1001;
}
</style>